package evtop

import (
	"github.com/pkg/errors"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/columnd"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/common"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/infod"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/interactiond"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/ddd"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/log"
)

func newColumnListener(d ddd.Domain) *columnListener {
	return &columnListener{
		base: base{
			d: d,
		},
		igar: d.SubDomain(interactiond.DomainID).AggregateRootByID(interactiond.Group).(interactiond.GroupAggregateRoot),
		car:  d.SubDomain(columnd.DomainID).AggregateRootByID(columnd.DomainID).(columnd.ColumnAggregateRoot),
		iar:  d.SubDomain(infod.DomainID).AggregateRootByID(infod.DomainID).(infod.InfoAggregateRoot),
		iiar: d.SubDomain(interactiond.DomainID).AggregateRootByID(interactiond.Interaction).(interactiond.InteractionAggregateRoot),
	}
}

type columnListener struct {
	base
	iiar interactiond.InteractionAggregateRoot
	iar  infod.InfoAggregateRoot
	car  columnd.ColumnAggregateRoot
	igar interactiond.GroupAggregateRoot
}

func (l columnListener) onColumnUpdateCtlParam() ddd.EventListener {
	return l.creEventListener(func(ctx ddd.Context, evt ddd.Event) error {
		log.Debugf("执行事件监听:columnListener onColumnUpdateCtlParam :%#v", evt)
		tmp, ok := evt.Data.(map[string]interface{})
		if !ok {
			return errors.Errorf("获取事件数据格式错误：%#v", evt.Data)

		}
		columnid := tmp["columnid"].(string)
		old := tmp["old"].(*columnd.ColumnCtlParam)
		new := tmp["new"].(*columnd.ColumnCtlParam)

		if old.IsReply == new.IsReply &&
			old.IsChk == new.IsChk &&
			equal(old.AllowIntCode, new.AllowIntCode) {
			return nil
		}

		sch := infod.InfoSearch{
			ColumnID: columnid,
			Status:   []infod.IStatus{infod.IStatusPublished},
		}
		c := interactiond.GroupCtrl{
			IsReplay:    new.IsReply,
			IsReplayChk: new.IsChk,
			AllowCodes:  new.AllowIntCode,
			Status:      interactiond.IGStatusNormal,
		}

		page := common.PageInfo{PageSize: 200, Mode: common.PageModeID}
		num := 0
		defer func() {
			log.Infof("成功更新［%d］个互动组控制参数．", num)
		}()
		for {
			_, rs, err := l.iar.QueryPage(ctx, sch, page)
			if err != nil {
				return errors.Wrapf(err, "迭代栏目内部信息失败")
			}
			if len(rs) == 0 {
				break
			}
			for _, r := range rs {
				page.PageID = r.InfoID
				//
				g, err := l.igar.GetIGroup2(ctx, interactiond.IGTTInfo, r.InfoID)
				if err != nil {
					return errors.Wrapf(err, "获取信息组失败")
				}
				if g == nil {
					continue
				}
				err = g.UpdateGroupCtrl(ctx, c)
				if err != nil {
					return errors.Wrapf(err, "更新互动组状态失败")
				}
				num++
			}

		}
		return nil
	})
}

func equal(a1 []string, a2 []string) bool {
	if len(a1) != len(a2) {
		return false
	}
one:
	for _, v := range a1 {
		for _, v2 := range a2 {
			if v2 == v {
				continue one
			}
		}
		return false
	}
	return true
}
